<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'phone' => ['required', 'string','unique:user','regex:/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/'],
            'yzm' => ['required', 'string','timeout','yzmgz',],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'code' => ['nullable','min:6','exists:user,code'],
        ],[
            'phone.required'=>'手机号不能为空',
            'phone.unique'=>'手机号已存在',
            'phone.regex'=>'手机号不正确',
            'yzm.required'=>'验证码不能为空',
            'yzm.yzmgz'=>'验证码不正确',
            'yzm.timeout'=>'验证码已过期',
            'password.required'=>'密码不能为空',
            'password.min'=>'密码最少为6位',
            'password.confirmed'=>'两次密码不一致',
            'code.min'=>'推荐码最小为6位',
            'code.exists'=>'推荐码不存在'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        if(empty($data['code'])){
            return User::create([
                'user_name' => $data['phone'],
                'phone' => $data['phone'],
                'password' => Hash::make($data['password']),
            ]);
        }else{
            $pid=User::where(['code'=>$data['code']])->first();
            $strPid=empty($pid['pid']) ? $pid['user_id']: $pid['pid'].','.$pid['user_id'];
            return User::create([
                'user_name' => $data['phone'],
                'phone' => $data['phone'],
                'password' => Hash::make($data['password']),
                'pid'=>$strPid,
            ]);
        }


    }
}
